package mediatheque.view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentListener;
import javax.swing.event.EventListenerList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;

import tools.DoubleClicEvent;
import tools.DoubleClicListener;

import mediatheque.model.GestionnaireModel;
import mediatheque.model.MediathequeModel;

public class GestionGestionnairesView extends JPanel implements Observer{
	
	private static final long serialVersionUID = 1L;

	private MediathequeModel model;
	
	private JScrollPane scrollTableau;
	private JTable tableauGestionnaires;
	
	private JLabel lblIdentifiant;
	private JLabel lblNom;
	private JLabel lblPrenom;
	private JLabel lblEmail;
	private JLabel lblLogin;
	
	private JPanel panneauRecherche;
	private JButton boutonReset;
	
	private JTextField tfIdentifiant;
	private JTextField tfNom;
	private JTextField tfPrenom;
	private JTextField tfEmail;
	private JTextField tfLogin;

	private JPanel panneauModification;
	private JButton boutonAjout;
	private JButton boutonModification;
	private JButton boutonSuppression;
	

	private EventListenerList listenerList;	
	
	
	public GestionGestionnairesView(MediathequeModel model) {
		this.model = model;
		
		model.addObserver(this);
		listenerList = new EventListenerList();	
		
		setPreferredSize(new Dimension(990, 650));
	
		lblIdentifiant = new JLabel("Identifiant : ");
		tfIdentifiant = new JTextField();        
		lblNom = new JLabel("Nom : ");
		tfNom = new JTextField();        
		lblPrenom = new JLabel("Prenom : ");
		tfPrenom = new JTextField();        
		lblEmail = new JLabel("Email : ");
		tfEmail = new JTextField();        
		lblLogin = new JLabel("Login : ");
		tfLogin = new JTextField();
		
		boutonReset = new JButton("Reset");
		
        
		boutonAjout = new JButton("Ajouter");
		boutonModification = new JButton("Modifier");
		boutonModification.setEnabled(false);
		boutonSuppression = new JButton("Supprimer");
		boutonSuppression.setEnabled(false);
		
		panneauModification = new JPanel();
		panneauModification.add(boutonAjout);
		panneauModification.add(boutonModification);
		panneauModification.add(boutonSuppression);
		
		
		tableauGestionnaires = new JTable();
		tableauGestionnaires.getTableHeader().setResizingAllowed(false);
		tableauGestionnaires.setRowHeight(25);
		tableauGestionnaires.setAutoCreateRowSorter(true);
		tableauGestionnaires.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent e) {
				if(e.getValueIsAdjusting())return;
			
				boolean afficher = !((ListSelectionModel)e.getSource()).isSelectionEmpty();
				boutonModification.setEnabled(afficher);
		        boutonSuppression.setEnabled(afficher);
			}
		});
		tableauGestionnaires.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.getClickCount() == 2) {
					int j = tableauGestionnaires.convertRowIndexToModel(tableauGestionnaires.rowAtPoint(e.getPoint()));
					fireMyEvent(new DoubleClicEvent(e.getSource(),(String) tableauGestionnaires.getModel().getValueAt(j, 0)));
				}
			}
		});
		
		setListeGestionnaires(model.getGestionnaires());
		scrollTableau = new JScrollPane(tableauGestionnaires);
		tableauGestionnaires.getTableHeader().setReorderingAllowed(false);
		
		TableColumn colonneIdentifiant = tableauGestionnaires.getColumnModel().getColumn(0);
		TableColumn colonneNom = tableauGestionnaires.getColumnModel().getColumn(1);
		TableColumn colonnePrenom = tableauGestionnaires.getColumnModel().getColumn(2);
		TableColumn colonneEmail = tableauGestionnaires.getColumnModel().getColumn(3);
		TableColumn colonneAdresse = tableauGestionnaires.getColumnModel().getColumn(4);
		TableColumn colonneEmprunt = tableauGestionnaires.getColumnModel().getColumn(5);

		Font fontBouton = new Font("Verdana", 0, 12);	
		// On fixe une largeur pour les colonnes
		colonneIdentifiant.setPreferredWidth(100);
		colonneNom.setPreferredWidth(190);
		colonnePrenom.setPreferredWidth(190);
		colonneEmail.setPreferredWidth(200);
		colonneAdresse.setPreferredWidth(200);
		colonneEmprunt.setPreferredWidth(110);

		// On centre le texte dans les colonnes
		DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();  
		dtcr.setHorizontalAlignment(SwingConstants.CENTER);
		dtcr.setFont(fontBouton);
		colonneIdentifiant.setCellRenderer(dtcr);
		colonneNom.setCellRenderer(dtcr);
		colonnePrenom.setCellRenderer(dtcr);
		colonneEmail.setCellRenderer(dtcr);
		colonneAdresse.setCellRenderer(dtcr);
		colonneEmprunt.setCellRenderer(dtcr);
		

		
	    placerComposants();
	}
	
	
	protected void placerComposants() {
		GroupLayout layout = new GroupLayout(this);
		this.setLayout(layout);
		layout.setHorizontalGroup(
			layout.createParallelGroup(GroupLayout.Alignment.LEADING)
			.addGroup(layout.createSequentialGroup()
				.addGap(289, 289, 289)
				.addComponent(boutonAjout)
				.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(boutonModification)
				.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(boutonSuppression)
				.addContainerGap(442, Short.MAX_VALUE))
				.addGroup(layout.createSequentialGroup()
				.addGap(38, 38, 38)
				.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
				.addGap(32, 32, 32)
				.addComponent(lblNom))
				.addComponent(lblIdentifiant))
				.addGap(18, 18, 18)
				.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
				.addComponent(tfNom)
				.addComponent(tfIdentifiant, GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE))
				.addGap(40, 40, 40)
				.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
				.addComponent(lblPrenom)
				.addComponent(lblEmail))
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
				.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
				.addComponent(tfEmail)
				.addComponent(tfPrenom, GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE))
				.addGap(67, 67, 67)
				.addComponent(lblLogin)
				.addGap(18, 18, 18)
				.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
				.addComponent(tfLogin, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE)
				.addComponent(boutonReset))
				.addGap(346, 346, 346))
				.addComponent(scrollTableau, GroupLayout.DEFAULT_SIZE, 995, Short.MAX_VALUE)
		);
		layout.setVerticalGroup(
			layout.createParallelGroup(GroupLayout.Alignment.LEADING)
			.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
				.addContainerGap()
				.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
				.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
				.addComponent(lblIdentifiant)
				.addComponent(tfIdentifiant, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
				.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
				.addComponent(lblNom)
				.addComponent(tfNom, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
				.addGroup(layout.createSequentialGroup()
				.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
				.addComponent(lblPrenom)
				.addComponent(tfPrenom, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
				.addComponent(lblLogin)
				.addComponent(tfLogin, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
				.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
				.addComponent(lblEmail)
				.addComponent(tfEmail, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
				.addComponent(boutonReset))))
				.addGap(18, 18, 18)
				.addComponent(scrollTableau, GroupLayout.DEFAULT_SIZE, 615, Short.MAX_VALUE)
				.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
				.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
				.addComponent(boutonAjout)
				.addComponent(boutonModification)
				.addComponent(boutonSuppression))
				.addContainerGap())
		);
	}
	
	
	

	void fireMyEvent(DoubleClicEvent evt) {
		Object[] listeners = listenerList.getListenerList();
		for (int i=0; i<listeners.length; i+=2) {
			if (listeners[i]==DoubleClicListener.class) {
				((DoubleClicListener)listeners[i+1]).onDoubleClic(evt);
			}
		}
	}
	
	public void addTousLesGestionnaireListener(ActionListener al){
		boutonReset.addActionListener(al);
	}
	public void addChangeChampsRechercheListener(DocumentListener dl) {
		tfNom.getDocument().addDocumentListener(dl);
		tfLogin.getDocument().addDocumentListener(dl);
		tfPrenom.getDocument().addDocumentListener(dl);	
		tfEmail.getDocument().addDocumentListener(dl);
		tfIdentifiant.getDocument().addDocumentListener(dl);	
	}
	public void addAjouterGestionnaireListener(ActionListener al){
		boutonAjout.addActionListener(al);
	}	
	
	public void addSupprimerGestionnaireListener(ActionListener al){
		boutonSuppression.addActionListener(al);
	}
	
	public void addModifierGestionnaireListener(ActionListener al){
		boutonModification.addActionListener(al);
	}
	
	public void addDoubleClicListener(DoubleClicListener mel){
		listenerList.add(DoubleClicListener.class, mel);
	}

	public String getValueNom(){
		return tfNom.getText();
	}
	public String getValueLogin(){
		return tfLogin.getText();
	}
	
	public void setListeGestionnaires(Collection<GestionnaireModel> listeGestionnaires){
		tableauGestionnaires.setModel(new GestionnairesTableModel(listeGestionnaires));
	}
	
	class GestionnairesTableModel extends AbstractTableModel{

		private static final long serialVersionUID = 1L;

		private String[] columnNames = {"Identifiant",
                						"Login",
                						"Nom",
                						"Prenom",
                						"Email",
                						"Adresse"};
		
		private List<GestionnaireModel> listeGestionnaires;
		
		public GestionnairesTableModel(Collection<GestionnaireModel> listeGestionnaires) {
			this.listeGestionnaires = new ArrayList<GestionnaireModel>(listeGestionnaires);
		}
		
		@Override
		public int getColumnCount() {
			return columnNames.length;
		}

		@Override
		public int getRowCount() {
			return listeGestionnaires.size();
		}
		
		@Override
		public String getColumnName(int column) {
			return columnNames[column];
		}

		@Override
		public Object getValueAt(int row, int col) {
			switch(col){
			case 0:
				return listeGestionnaires.get(row).getIdentifiant();
			case 1:
				return listeGestionnaires.get(row).getLogin();
			case 2:
				return listeGestionnaires.get(row).getNom();
			case 3:
				return listeGestionnaires.get(row).getPrenom();
			case 4:
				return listeGestionnaires.get(row).getEmail();
			case 5:
				return listeGestionnaires.get(row).getAdresse();	
			}
			return null;
		}
		
	}
	public List<String> getListeGestionnairesSelectionne() {
		List<String> listeGestionnaires = new ArrayList<String>();
		int j = 0;
		for (int i = 0; i < tableauGestionnaires.getModel().getRowCount(); i++) {
			j = tableauGestionnaires.convertRowIndexToModel(i);
			if(tableauGestionnaires.getSelectionModel().isSelectedIndex(i)){
				listeGestionnaires.add((String) tableauGestionnaires.getModel().getValueAt(j, 0));
			}			
		}
			
		return listeGestionnaires;
	}
	@Override
	public void update(Observable o, Object arg) {
		if((Integer)arg == MediathequeModel.GESTIONNAIRE){
			setListeGestionnaires(model.getGestionnaires());
		}
	}

	public String getValeurIdentifiant(){
		return tfIdentifiant.getText();
	}
	public String getValeurEmail(){
		return tfEmail.getText();
	}
	public String getValeurPrenom() {
		return tfPrenom.getText();
	}
	public void setValeurPrenom(String s) {
		tfPrenom.setText(s);
	}
	public void setValeurNom(String s) {
		tfNom.setText(s);
	}
	public void setValeurLogin(String s) {
		tfLogin.setText(s);
	}
	public void setValeurIdentifiant(String s) {
		tfIdentifiant.setText(s);
	}
	public void setValeurEmail(String s) {
		tfEmail.setText(s);
	}
}
